[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  23. import type { CrowiRequest } from '~/interfaces/crowi-request';
  24. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  25. // import { useRendererSettings } from '~/stores/renderer';
  26. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  27. import type { EditorConfig } from '~/interfaces/editor-settings';
  28. import type { CustomWindow } from '~/interfaces/global';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  36. import { useRedirectFrom } from '~/stores/page-redirect';
  37. import {
  38. EditorMode,
  39. useEditorMode, useSelectedGrant,
  40. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  41. } from '~/stores/ui';
  42. import loggerFactory from '~/utils/logger';
  43. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  44. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  45. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  46. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  49. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  50. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  51. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  52. import {
  53. useCurrentUser,
  54. useIsLatestRevision,
  55. useIsForbidden, useIsNotFound, useIsSharedUser,
  56. useIsEnabledStaleNotification, useIsIdenticalPath,
  57. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  58. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  59. useIsAclEnabled, useIsSearchPage,
  60. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  61. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  62. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  63. } from '../stores/context';
  64. import {
  65. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  66. } from './utils/commons';
  67. // import { useCurrentPageSWR } from '../stores/page';
  68. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  69. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  70. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  71. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  72. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  73. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  74. const logger = loggerFactory('growi:pages:all');
  75. const {
  76. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  77. } = pagePathUtils;
  78. const { removeHeadingSlash } = pathUtils;
  79. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  80. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  81. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  82. {
  83. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  84. return v?.data != null
  85. && v?.data.toObject != null
  86. && v?.meta != null
  87. && isIPageInfoForEntity(v.meta);
  88. },
  89. serialize: (v) => {
  90. return {
  91. data: superjson.stringify(v.data.toObject()),
  92. meta: superjson.stringify(v.meta),
  93. };
  94. },
  95. deserialize: (v) => {
  96. return {
  97. data: superjson.parse(v.data),
  98. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  99. };
  100. },
  101. },
  102. 'IPageToShowRevisionWithMetaTransformer',
  103. );
  104. const IdenticalPathPage = (): JSX.Element => {
  105. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  106. return <IdenticalPathPage />;
  107. };
  108. const PutbackPageModal = (): JSX.Element => {
  109. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  110. return <PutbackPageModal />;
  111. };
  112. type Props = CommonProps & {
  113. currentUser: IUser,
  114. pageWithMeta: IPageToShowRevisionWithMeta | null,
  115. // pageUser?: any,
  116. redirectFrom?: string;
  117. // shareLinkId?: string;
  118. isLatestRevision?: boolean
  119. isIdenticalPathPage?: boolean,
  120. isForbidden: boolean,
  121. isNotFound: boolean,
  122. isNotCreatablePage: boolean,
  123. // isAbleToDeleteCompletely: boolean,
  124. isSearchServiceConfigured: boolean,
  125. isSearchServiceReachable: boolean,
  126. isSearchScopeChildrenAsDefault: boolean,
  127. isSlackConfigured: boolean,
  128. // isMailerSetup: boolean,
  129. isAclEnabled: boolean,
  130. // hasSlackConfig: boolean,
  131. drawioUri: string,
  132. hackmdUri: string,
  133. noCdn: string,
  134. // highlightJsStyle: string,
  135. isAllReplyShown: boolean,
  136. isContainerFluid: boolean,
  137. editorConfig: EditorConfig,
  138. isEnabledStaleNotification: boolean,
  139. // isEnabledLinebreaks: boolean,
  140. // isEnabledLinebreaksInComments: boolean,
  141. adminPreferredIndentSize: number,
  142. isIndentSizeForced: boolean,
  143. disableLinkSharing: boolean,
  144. rendererConfig: RendererConfig,
  145. // UI
  146. userUISettings?: IUserUISettings
  147. // Sidebar
  148. sidebarConfig: ISidebarConfig,
  149. };
  150. const GrowiPage: NextPage<Props> = (props: Props) => {
  151. // const { t } = useTranslation();
  152. const router = useRouter();
  153. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  154. // register global EventEmitter
  155. if (isClient()) {
  156. (window as CustomWindow).globalEmitter = new EventEmitter();
  157. }
  158. // commons
  159. useEditorConfig(props.editorConfig);
  160. useCsrfToken(props.csrfToken);
  161. useCustomizedLogoSrc(props.customizedLogoSrc);
  162. // UserUISettings
  163. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  164. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  165. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  166. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  167. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  168. // page
  169. useIsLatestRevision(props.isLatestRevision);
  170. useIsContainerFluid(props.isContainerFluid);
  171. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  172. useIsForbidden(props.isForbidden);
  173. useIsNotFound(props.isNotFound);
  174. // useIsNotCreatable(props.IsNotCreatable);
  175. useRedirectFrom(props.redirectFrom);
  176. // useShared();
  177. // useShareLinkId(props.shareLinkId);
  178. useIsSharedUser(false); // this page cann't be routed for '/share'
  179. useIsIdenticalPath(false); // TODO: need to initialize from props
  180. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  181. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  182. useIsSearchPage(false);
  183. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  184. useIsSearchServiceReachable(props.isSearchServiceReachable);
  185. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  186. useIsSlackConfigured(props.isSlackConfigured);
  187. // useIsMailerSetup(props.isMailerSetup);
  188. useIsAclEnabled(props.isAclEnabled);
  189. // useHasSlackConfig(props.hasSlackConfig);
  190. useDrawioUri(props.drawioUri);
  191. useHackmdUri(props.hackmdUri);
  192. // useNoCdn(props.noCdn);
  193. useDefaultIndentSize(props.adminPreferredIndentSize);
  194. useIsIndentSizeForced(props.isIndentSizeForced);
  195. useDisableLinkSharing(props.disableLinkSharing);
  196. useRendererConfig(props.rendererConfig);
  197. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  198. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  199. useIsAllReplyShown(props.isAllReplyShown);
  200. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  201. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  202. const { pageWithMeta, userUISettings } = props;
  203. const pageId = pageWithMeta?.data._id;
  204. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  205. useCurrentPageId(pageId ?? null);
  206. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  207. useCurrentPathname(props.currentPathname);
  208. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  209. useEditingMarkdown(pageWithMeta?.data.revision?.body ?? '');
  210. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  211. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  212. const { getClassNamesByEditorMode } = useEditorMode();
  213. const shouldRenderPutbackPageModal = pageWithMeta != null
  214. ? _isTrashPage(pageWithMeta.data.path)
  215. : false;
  216. // sync grant data
  217. useEffect(() => {
  218. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  219. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  220. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  221. useEffect(() => {
  222. const decodedURI = decodeURI(window.location.pathname);
  223. if (isClient() && decodedURI !== props.currentPathname) {
  224. router.replace(props.currentPathname, undefined, { shallow: true });
  225. }
  226. }, [props.currentPathname, router]);
  227. const classNames: string[] = [];
  228. const isSidebar = pagePath === '/Sidebar';
  229. classNames.push(...getClassNamesByEditorMode(isSidebar));
  230. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  231. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  232. ? null
  233. : currentPage.expandContentWidth;
  234. const isContainerFluidDefault = props.isContainerFluid;
  235. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  236. return (
  237. <>
  238. <Head>
  239. {/*
  240. {renderScriptTagByName('drawio-viewer')}
  241. {renderScriptTagByName('highlight-addons')}
  242. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  243. */}
  244. </Head>
  245. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={isContainerFluid}>
  246. <div className="h-100 d-flex flex-column justify-content-between">
  247. <header className="py-0 position-relative">
  248. <div id="grw-subnav-container">
  249. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  250. </div>
  251. </header>
  252. <div className="d-edit-none">
  253. <GrowiSubNavigationSwitcher />
  254. </div>
  255. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  256. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  257. <div className="flex-grow-1">
  258. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  259. <div id="content-main" className="content-main grw-container-convertible">
  260. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  261. { !props.isIdenticalPathPage && (
  262. <>
  263. <PageAlerts />
  264. { props.isForbidden && <ForbiddenPage /> }
  265. { props.isNotCreatablePage && <NotCreatablePage />}
  266. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  267. {/* <DisplaySwitcher /> */}
  268. {/* <PageStatusAlert /> */}
  269. </>
  270. ) }
  271. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  272. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  273. <div id="revision-toc-content" className="revision-toc-content"></div>
  274. </div>
  275. </div> */}
  276. </div>
  277. </div>
  278. </div>
  279. { !props.isIdenticalPathPage && !props.isNotFound && (
  280. <footer className="footer d-edit-none">
  281. { pageWithMeta != null && !isTopPagePath && (<Comments pageId={pageId} revision={pageWithMeta.data.revision} />) }
  282. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  283. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  284. ) }
  285. <CurrentPageContentFooter />
  286. </footer>
  287. )}
  288. <UnsavedAlertDialog />
  289. <DescendantsPageListModal />
  290. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  291. </div>
  292. </BasicLayout>
  293. </>
  294. );
  295. };
  296. function getPageIdFromPathname(currentPathname: string): string | null {
  297. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  298. }
  299. class MultiplePagesHitsError extends ExtensibleCustomError {
  300. pagePath: string;
  301. constructor(pagePath: string) {
  302. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  303. this.pagePath = pagePath;
  304. }
  305. }
  306. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  307. const { model: mongooseModel } = await import('mongoose');
  308. const req: CrowiRequest = context.req as CrowiRequest;
  309. const { crowi } = req;
  310. const { revisionId } = req.query;
  311. const Page = crowi.model('Page') as PageModel;
  312. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  313. const { pageService } = crowi;
  314. let currentPathname = props.currentPathname;
  315. const pageId = getPageIdFromPathname(currentPathname);
  316. const isPermalink = _isPermalink(currentPathname);
  317. const { user } = req;
  318. if (!isPermalink) {
  319. // check redirects
  320. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  321. if (chains != null) {
  322. // overwrite currentPathname
  323. currentPathname = chains.end.toPath;
  324. props.currentPathname = currentPathname;
  325. // set redirectFrom
  326. props.redirectFrom = chains.start.fromPath;
  327. }
  328. // check whether the specified page path hits to multiple pages
  329. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  330. if (count > 1) {
  331. throw new MultiplePagesHitsError(currentPathname);
  332. }
  333. }
  334. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  335. const page = pageWithMeta?.data as unknown as PageDocument;
  336. // add user to seen users
  337. if (page != null && user != null) {
  338. await page.seen(user);
  339. }
  340. // populate & check if the revision is latest
  341. if (page != null) {
  342. page.initLatestRevisionField(revisionId);
  343. await page.populateDataToShowRevision();
  344. props.isLatestRevision = page.isLatestRevision();
  345. }
  346. props.pageWithMeta = pageWithMeta;
  347. }
  348. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  349. const { model: mongooseModel } = await import('mongoose');
  350. const req = context.req as CrowiRequest<IUserHasId & any>;
  351. const { user } = req;
  352. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  353. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  354. if (userUISettings != null) {
  355. props.userUISettings = userUISettings.toObject();
  356. }
  357. }
  358. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  359. const req: CrowiRequest = context.req as CrowiRequest;
  360. const { crowi } = req;
  361. const Page = crowi.model('Page') as PageModel;
  362. const { currentPathname } = props;
  363. const pageId = getPageIdFromPathname(currentPathname);
  364. const isPermalink = _isPermalink(currentPathname);
  365. const page = props.pageWithMeta?.data;
  366. if (props.isIdenticalPathPage) {
  367. // TBD
  368. }
  369. else if (page == null) {
  370. props.isNotFound = true;
  371. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  372. // check the page is forbidden or just does not exist.
  373. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  374. props.isForbidden = count > 0;
  375. }
  376. else {
  377. props.isNotFound = page.isEmpty;
  378. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  379. if (isPermalink && page.isEmpty) {
  380. props.currentPathname = page.path;
  381. }
  382. // /path/to/page ==> /62a88db47fed8b2d94f30000
  383. if (!isPermalink && !page.isEmpty) {
  384. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  385. if (!isToppage) {
  386. props.currentPathname = `/${page._id}`;
  387. }
  388. }
  389. }
  390. }
  391. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  392. // const req: CrowiRequest = context.req as CrowiRequest;
  393. // const { crowi } = req;
  394. // const UserModel = crowi.model('User');
  395. // if (isUserPage(props.currentPagePath)) {
  396. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  397. // if (user != null) {
  398. // props.pageUser = JSON.stringify(user.toObject());
  399. // }
  400. // }
  401. // }
  402. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  403. const req: CrowiRequest = context.req as CrowiRequest;
  404. const { crowi } = req;
  405. const {
  406. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  407. } = crowi;
  408. props.isSearchServiceConfigured = searchService.isConfigured;
  409. props.isSearchServiceReachable = searchService.isReachable;
  410. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  411. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  412. // props.isMailerSetup = mailService.isMailerSetup;
  413. props.isAclEnabled = aclService.isAclEnabled();
  414. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  415. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  416. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  417. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  418. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  419. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  420. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  421. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  422. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  423. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  424. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  425. props.editorConfig = {
  426. upload: {
  427. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  428. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  429. },
  430. };
  431. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  432. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  433. props.rendererConfig = {
  434. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  435. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  436. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  437. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  438. plantumlUri: process.env.PLANTUML_URI ?? null,
  439. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  440. // XSS Options
  441. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  442. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  443. tagWhiteList: crowi.xssService.getTagWhiteList(),
  444. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  445. };
  446. props.sidebarConfig = {
  447. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  448. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  449. };
  450. }
  451. /**
  452. * for Server Side Translations
  453. * @param context
  454. * @param props
  455. * @param namespacesRequired
  456. */
  457. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  458. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  459. props._nextI18Next = nextI18NextConfig._nextI18Next;
  460. }
  461. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  462. const req = context.req as CrowiRequest<IUserHasId & any>;
  463. const { user } = req;
  464. const result = await getServerSideCommonProps(context);
  465. // check for presence
  466. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  467. if (!('props' in result)) {
  468. throw new Error('invalid getSSP result');
  469. }
  470. const props: Props = result.props as Props;
  471. if (props.redirectDestination != null) {
  472. return {
  473. redirect: {
  474. permanent: false,
  475. destination: props.redirectDestination,
  476. },
  477. };
  478. }
  479. if (user != null) {
  480. props.currentUser = user.toObject();
  481. }
  482. try {
  483. await injectPageData(context, props);
  484. }
  485. catch (err) {
  486. if (err instanceof MultiplePagesHitsError) {
  487. props.isIdenticalPathPage = true;
  488. }
  489. else {
  490. throw err;
  491. }
  492. }
  493. await injectUserUISettings(context, props);
  494. await injectRoutingInformation(context, props);
  495. injectServerConfigurations(context, props);
  496. await injectNextI18NextConfigurations(context, props, ['translation']);
  497. return {
  498. props,
  499. };
  500. };
  501. export default GrowiPage;